<template>
  <el-drawer v-model="visible" title="" size="100%" :before-close="handleClose" custom-class="user-center-drawer"
    :with-header="false">
    <div class="user-center-container">
      <!-- 可拖拽区 -->
      <div class="drag-area" ref="dragAreaBox" @mousedown="handleMouseDown" @mousemove="handleMouseMove"
        @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
      </div>

      <!-- 侧边菜单  -->
      <div class="sidebar">
        <el-menu :default-active="currentTab" :model-value="currentTab" class="user-center-menu"
          @select="handleMenuSelect" background-color="#070809" text-color="#949495" active-text-color="#ffffff">
          <el-menu-item-group :title="item.title" :index="item.index" v-for="(item, index) in MenuList"
            :key="item.index" @click="activeIndex = item.index">
            <el-menu-item :index="o.id" v-for="(o, i) in item.list" :key="o.name" @click="activeIndex = o.id">
              <div class="item-active-bg">
                <!-- <el-icon>
              <component :is="item.icon" />
            </el-icon> -->

                <img :src="getMenuItemIcon(o.name, o.id)" class="menu-icon" width="24" height="24" alt="menu icon" />
                <span>{{ o.title }}</span>
              </div>
            </el-menu-item>
          </el-menu-item-group>
        </el-menu>
      </div>

      <!-- 主内容区域 -->
      <div class="content-area">
        <div class="close-btn" @click="handleClose">
          <CircleClose />
          <span class="title">ESC</span>
        </div>
        <div v-if="currentTab === '1'" class="page-content">
          <!-- <h2>账单明细</h2> -->
          <BillDetails />
        </div>

        <div v-else-if="currentTab === '2'" class="page-content">
          <!-- <h2>我的订单</h2> -->
          <MyOrder />
        </div>

        <div v-else-if="currentTab === '3'" class="page-content">
          <!-- <h2>账号设置</h2> -->
          <AccountSettings @close="handleClose" />
        </div>

        <div v-else-if="currentTab === '4'" class="page-content">
          <!-- <h2>帮助与反馈</h2> -->
          <HelpAndFeedback />
        </div>

        <div v-else-if="currentTab === '5'" class="page-content">
          <!-- <h2>系统设置</h2> -->
          <SystemSettings />
        </div>

        <div v-else-if="currentTab === '6'" class="page-content">
          <!-- <h2>关于我们</h2> -->
          <AboutUs />
        </div>
      </div>



    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useUserStore } from '../../stores/user'
import { User, Document, CreditCard, Setting, Help } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import BillDetails from './BillDetails/Index.vue'
import MyOrder from './MyOrder/Index.vue'
import AccountSettings from './AccountSettings/Index.vue'
import HelpAndFeedback from './HelpAndFeedback/Index.vue'
import SystemSettings from './SystemSettings/Index.vue'
import AboutUs from './AboutUs/Index.vue'

import BillDetailsImg from '@/assets/images/usercenter/sidebar/BillDetails.png'
import BillDetailsActiveImg from '@/assets/images/usercenter/sidebar/BillDetails_active.png'
import MyOrderImg from '@/assets/images/usercenter/sidebar/MyOrder.png'
import MyOrderActiveImg from '@/assets/images/usercenter/sidebar/MyOrder_active.png'
import AccountSettingsImg from '@/assets/images/usercenter/sidebar/AccountSettings.png'
import AccountSettingsActiveImg from '@/assets/images/usercenter/sidebar/AccountSettings_active.png'
import HelpAndFeedbackImg from '@/assets/images/usercenter/sidebar/HelpAndFeedback.png'
import HelpAndFeedbackActiveImg from '@/assets/images/usercenter/sidebar/HelpAndFeedback_active.png'
import SystemSettingsImg from '@/assets/images/usercenter/sidebar/SystemSettings.png'
import SystemSettingsActiveImg from '@/assets/images/usercenter/sidebar/SystemSettings_active.png'
import AboutUsImg from '@/assets/images/usercenter/sidebar/AboutUs.png'
import AboutUsActiveImg from '@/assets/images/usercenter/sidebar/AboutUs_active.png'

const route = useRoute()

// 定义 refs
const dragAreaBox = ref(null)
// 拖拽功能相关变量
let isDragging = false
let startX = 0
let startY = 0
// 节流相关变量
let lastMoveTime = 0
const moveThrottleMs = 16 // 约60fps，16ms间隔

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentTab: {
    type: String,
    default: '1'
  }
})

const MenuList = ref([{
  index: 1,
  group: 'my',
  title: '我的',
  list: [
    {
      id: '1',
      title: '账单明细',
      name: 'BillDetails',
      icon: User
    },
    {
      id: '2',
      title: '我的订单',
      name: 'MyOrder',
      icon: User
    }]
}, {
  index: 2,
  group: 'setting',
  title: '设置',
  list: [
    {
      id: '3',
      title: '账户设置',
      name: 'AccountSettings',
      icon: Setting
    },
    {
      id: '4',
      title: '帮助与反馈',
      name: 'HelpAndFeedback',
      icon: Help
    },
    {
      id: '5',
      title: '系统设置',
      name: 'SystemSettings',
      icon: Setting
    },
    {
      id: '6',
      title: '关于我们',
      name: 'AboutUs',
      icon: Document
    }
  ]
}])
const activeIndex = ref('1')

// Emits
const emit = defineEmits(['update:modelValue', 'close', 'update:currentTab'])

// Refs
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const accountFormRef = ref()
const feedbackFormRef = ref()

// Store
const userStore = useUserStore()

// 使用 props 中的 currentTab，确保受父组件控制
const userInfo = computed(() => userStore.userInfo)

const accountSettings = ref({
  twoFactorAuth: false
})

const feedbackForm = ref({
  type: '',
  content: '',
  contact: ''
})

// 菜单图标
const getMenuItemIcon = (name, id) => {
  if (name === 'BillDetails') {
    return id === props.currentTab ? BillDetailsActiveImg : BillDetailsImg
  } else if (name === 'MyOrder') {
    return id === props.currentTab ? MyOrderActiveImg : MyOrderImg
  } else if (name === 'AccountSettings') {
    return id === props.currentTab ? AccountSettingsActiveImg : AccountSettingsImg
  } else if (name === 'HelpAndFeedback') {
    return id === props.currentTab ? HelpAndFeedbackActiveImg : HelpAndFeedbackImg
  } else if (name === 'SystemSettings') {
    return id === props.currentTab ? SystemSettingsActiveImg : SystemSettingsImg
  } else if (name === 'AboutUs') {
    return id === props.currentTab ? AboutUsActiveImg : AboutUsImg
  }

  return BillDetailsImg
}

// 方法
const handleClose = () => {
  emit('close')
}

const handleMenuSelect = (index) => {
  // 当用户在组件内选择菜单项时，通知父组件更新 currentTab
  emit('update:currentTab', index)
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
    }
  })
}

const searchBill = () => {
  ElMessage.success('查询成功')
  // 这里可以添加实际的查询逻辑
}

const openChangePasswordDialog = () => {
  ElMessage.info('打开修改密码弹窗')
  // 这里可以添加打开修改密码弹窗的逻辑
}

const openChangePayPasswordDialog = () => {
  ElMessage.info('打开修改支付密码弹窗')
  // 这里可以添加打开修改支付密码弹窗的逻辑
}

const submitFeedback = () => {
  feedbackFormRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('反馈提交成功')
      feedbackForm.value = {
        type: '',
        content: '',
        contact: ''
      }
    }
  })
}

// 初始化拖拽功能
const initializeDragFunctionality = () => {
  console.log('初始化头部拖拽功能')

  const dragArea = dragAreaBox.value

  if (!dragArea) {
    console.error('找不到拖拽区域元素')
    return
  }

  // 设置拖动样式
  // dragArea.style.cursor = 'move'
  dragArea.style.webkitAppRegion = 'no-drag' // 确保不会与CSS的app-region冲突

  // 添加鼠标按下事件监听器
  dragArea.addEventListener('mousedown', handleMouseDown)
}

// 处理鼠标按下事件
const handleMouseDown = (e) => {
  // 检查是否点击在排除元素上（按钮等）
  const excludeElements = [
    'button',
    'input',
    'svg',
    '.el-button',
    '.search-container',
    '.coin-balance',
    '.user-avatar-container'
  ]

  const isExcluded = excludeElements.some(selector =>
    e.target.closest && e.target.closest(selector)
  )

  if (isExcluded) {
    console.log('点击在排除元素上，不触发拖拽')
    return
  }

  // console.log('头部拖动开始:', e.clientX, e.clientY)
  isDragging = true
  startX = e.clientX
  startY = e.clientY
  lastMoveTime = 0 // 重置节流时间，确保首次移动立即响应

  // 通知C#开始拖动
  if (window.chrome && window.chrome.webview) {
    window.chrome.webview.postMessage({
      action: 'startDrag',
      x: e.screenX,
      y: e.screenY
    })
  }

  e.preventDefault()
}

// 鼠标移动事件处理
const handleMouseMove = (e) => {
  if (isDragging) {
    const currentTime = Date.now()

    // 节流处理：只有当时间间隔大于阈值时才发送消息
    if (currentTime - lastMoveTime >= moveThrottleMs) {
      const deltaX = e.clientX - startX
      const deltaY = e.clientY - startY

      // 通知C#移动窗口
      if (window.chrome && window.chrome.webview) {
        window.chrome.webview.postMessage({
          action: 'dragMove',
          deltaX: deltaX,
          deltaY: deltaY,
          screenX: e.screenX,
          screenY: e.screenY
        })
      }

      lastMoveTime = currentTime
    }
  }
}

// 鼠标释放事件处理
const handleMouseUp = (e) => {
  if (isDragging) {
    console.log('头部拖动结束')
    isDragging = false

    // 通知C#结束拖动
    if (window.chrome && window.chrome.webview) {
      window.chrome.webview.postMessage({
        action: 'endDrag'
      })
    }
  }
}
onMounted(() => {
  // 初始化拖拽功能
  // initializeDragFunctionality()


})

// 在组件卸载前清理事件监听器
onBeforeUnmount(() => {

})

</script>

<style lang="scss" scoped>
.drag-area {
  width: 95%;
  height: 80px;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1000;
}

.user-center-container {
  display: flex;
  height: 100%;
}

.sidebar {
  width: 153px;
  background-color: #070809;
  box-sizing: border-box;
}

.user-info {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-lg {
  width: 60px;
  height: 60px;
  margin: 0 auto 10px;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
}

.user-center-menu {
  // margin-top: 30px;
  margin-top: 30px;
  border-right: none;
  background-color: transparent;

  :deep(.el-menu-item-group__title) {
    margin-top: 20px;
    margin-left: 10px;
  }

  .el-menu-item {
    color: #949495;
    height: 44px;
    line-height: 44px;
    font-size: 14px;
    transition: all 0.3s;
    position: relative;
    margin-top: 15px;
    font-weight: bold;
    padding: 0 10px 0 12px;

    &:hover {
      .item-active-bg {
        background: rgba(255, 255, 255, 0.1)
      }
    }

    &.is-active::before {
      content: ' ';
      width: 6px;
      height: 26px;
      background-color: #ffd700;
      left: 0;
      position: absolute;
      border-radius: 0 4px 4px 0;
    }

    .item-active-bg {
      width: 132px;
      height: 44px;
      line-height: 44px;
      display: flex;
      align-items: center;
      padding-left: 10px;
      box-sizing: border-box;
      border-radius: 3px;
    }

    &.is-active .item-active-bg {
      color: #fff;
      background: rgba(255, 255, 255, 0.1)
    }

    .menu-icon {
      width: 24px;
      height: 24px;
      display: block;
      margin-right: 5px;
    }
  }
}

.content-area {
  flex: 1;
  background-color: #121517;
  padding: 20px;
  overflow-y: auto;

  .close-btn {
    display: flex;
    flex-direction: column;
    line-height: 16px;
    position: absolute;
    top: 30px;
    right: 30px;
    font-size: 14px;
    color: #888;
    cursor: pointer;
  }
}

.page-content {
  height: 100%;
}

.page-content h2 {
  margin-bottom: 20px;
  color: #fff;
}

.bill-filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table__header th) {
  background-color: #3a3d3f;
  color: #ccc;
  border-bottom: 1px solid #4a4d4f;
}

:deep(.el-table__body tr) {
  background-color: #292c2e;
  color: #ddd;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #3a3d3f;
}

:deep(.el-form-item__label) {
  color: #ccc;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: #3a3d3f;
  border-color: #4a4d4f;
}

:deep(.el-select__placeholder),
:deep(.el-select__input),
:deep(.el-textarea__inner) {
  color: #ddd;
}

:deep(.el-card) {
  background-color: #3a3d3f;
  border-color: #4a4d4f;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #4a4d4f;
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
}

.el-drawer__body {
  padding: 0 !important;
}
</style>